package com.example.jdk8;

import com.example.jdk8.interface_test.Formula;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class LambdaTest {
    public static void main(String[] args) {
        /**
         * jdk8 之前比较列表中的两个元素
         */
        List<String> names = Arrays.asList("peter", "anna", "mike", "xenia");
        Collections.sort(names, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o2.compareTo(o1);
            }
        });


        List<String> list = Arrays.asList("12333", "12334", "12335", "12336");
        /**
         * 使用lambda 表达式
         */
        Collections.sort(list, (String a1, String a2) -> {
            return a1.compareTo(a2);
        });

        // 如果代码块中只有一行代码，可以简化成
        Collections.sort(list, (a, b) -> a.compareTo(b));

        // 31 行代码更加简练
        Collections.sort(list, String::compareTo);
    }
}

class Something {
    String startWith(String s) {
        return String.valueOf(s.charAt(0));
    }

    public static void main(String[] args) {
        // 测试接口 Converter
        Converter<String, Integer> converter = (from) -> Integer.valueOf(from);
        Integer converted = converter.convert("123");
        System.out.println(converted);

        // 测试 Something
        Something something = new Something();
        Converter<String, String> converter1 = something::startWith;
        String java = converter1.convert("Java");
        System.out.println(java);

        // 访问外部变量
        final int num = 3;
        Converter<Integer, String> stringConverter = (from) -> String.valueOf(Integer.valueOf(from + num));
        Integer result = Integer.valueOf(stringConverter.convert(2));
        System.out.println("result ---> " + result);

        // 非final 变量访问
        int num1 = 1;
        stringConverter = (from) -> String.valueOf(Integer.valueOf(from + num1));
        String convert = stringConverter.convert(1);
        System.out.println("covert -------> " + convert);
    }
}

/**
 * 访问成员变量和静态变量
 */
class Lambda4 {
    static int outerStaticNum;
    int outerNum;

    void testScopes() {
        Converter<Integer, String> stringConverter = (from) -> {
            outerNum = 23;
            return String.valueOf(from);
        };

        Converter<Integer, String> stringConverter2 = (from) -> {
            outerStaticNum = 72;
            return String.valueOf(from);
        };
    }

    public static void main(String[] args) {
        /**
         * jdk8 之前的写法
         */
        Formula formula = new Formula() {
            @Override
            public double calculate(int a) {
                return 0;
            }
        };

        /**
         * jdk8 之后的写法
         */
        formula = a -> 3;
    }
}
